const CommonUtils = require("./utils/index");
const CommonMixins = require("./mixins/index");
const CommonServices = require("./services/index");
const CommonComponents = require("./components/index");

const ConfigModel = require("./configModel");
let _isReady = false;
let _observerList = [];

/**
 * 监听LeeCommonJs库是否加载完成
 * @param {Object} callback
 */
function onReady(callback) {
	if (typeof callback == 'function') {
		if (_isReady) {
			setTimeout(() => {
				callback();
			}, 0)
		} else {
			_observerList.push(callback)
		}
	} else {
		throw new Error('lee-common-js onReady function need a callback fn param');
	}
}

/**
 * 触发LeeCommonJs库加载完成事件
 */
function triggerReady() {
	_isReady = true;
	while (_observerList.length) {
		let callback = _observerList.shift();
		callback();
	}
}
let _configData;
/**
 * 注册LeeCommonJs库
 * 
 * 该函数用于初始化配置数据，可以根据传入的配置对象创建配置模型
 * 具体配置项请参考  /configModel.js  或者 /static/lee-common-js-config-template.js
 * 
 * @param {Object} config
 */
function registerLeeCommonJs(config) {
	if (!config || !(config instanceof ConfigModel)) {
		throw new Error('leeCommonjs registerLeeCommonJs config must be an instance of ConfigModel');
	}
	_configData = config
	_registerSubModules(_configData);
}

/**
 * 注册leeCommonJs子模块
 * 
 * @param {Object} configData - 配置对象
 */
function _registerSubModules(configData) {
	CommonUtils.registerModule(configData);
	CommonMixins.registerModule(configData);
	CommonServices.registerModule(configData);
	CommonComponents.registerModule(configData);
	triggerReady();
}

module.exports = {
	registerLeeCommonJs,
	onReady
}